const path = require('path');
const iconv = require('iconv-lite');
const fs = require('fs');

function toutf8() {
    if (process.env.NODE_ENV === 'production') {
        privateToUtf8(path.dirname(process.execPath) + '/resources/data/config.ini');
    } else {
        privateToUtf8('./data/config_test.ini');
    }
}

function privateToUtf8(fileName) {
    const filePath = fileName;
    const outFilePath = fileName;
    let byte = fs.readFileSync(filePath);
    if ((byte[0] === 0xef && byte[1] === 0xbb) ||
        (byte[0] === 0xfe && byte[1] === 0xff) ||
        (byte[0] === 0xff && byte[1] === 0xfe)
    ) {
        // 已经是utf8
        console.log('object fileName 已经是utf-8', fileName);
        // fs.writeFileSync(outFilePath, byte);
        return;
    }
    fs.renameSync(filePath, filePath + ".bak");
    byte = iconv.decode(byte, 'gbk');
    const content = '\ufeff' + byte.toString('utf8');

    fs.writeFileSync(outFilePath, content);
}

module.exports = toutf8;
